import { Button, Input, message, Tabs } from 'antd';
import Back from '../datasets/components/Back';
import { memo, useEffect, useMemo, useState } from 'react';
import { CSSProperties } from 'styled-components';
import Metadata from './components/metadata';
// import Chunks from './components/chunks';
// import PreviewCollcection from './components/preview-collection';
import { useParams } from '@/router/hooks';
import CollectionHeader from './components/header';
import NewChunkModal from './components/chunks/NewChunkModal';
import datasetService from '@/api/services/datasetService';
import CollectionContextProvider, { CollectionContext } from './context';
import { useContextSelector } from 'use-context-selector';
import { CollectionEvent } from '@/types/dataset';
import React from 'react';
import { useSettings } from '@/store/settingStore';
import { DatasetCollectionTypeEnum, ThemeLayout } from '@/types/enum';
import TabMenus from '../components/tab-menus/TabMenus';
import './styles/collection-detail.scss';
import { Ellipsis } from 'antd-mobile';

const Chunks = React.lazy(() => import('./components/chunks'));
const PreviewCollection = React.lazy(() => import('./components/preview-collection'));

interface Props {
  collectionId?: string;
  name?: string;
  onBack?: () => void;
}

interface Menu {
  key: number;
  title: string;
  // content: React.ReactNode;
}

const ChunksDetail = memo(({ collectionId, name, onBack }: Props) => {
  // const { collectionId = propCollectionId, name = propName } = useParams() as {
  //   collectionId: string;
  //   name: string;
  // };
  const [newChunkModal, setNewChunkModal] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [activeKeys, setActiveKeys] = useState<Set<number>>(new Set());
  const [selectedIndex, setSelectedIndex] = useState(0);
  const { event$, collectionData, setName, setCollectionId } = useContextSelector(
    CollectionContext,
    (s) => s,
  );
  const { themeLayout } = useSettings();
  const menus: Menu[] = useMemo(() => {
    if (
      collectionData?.type === DatasetCollectionTypeEnum.file ||
      collectionData?.type === DatasetCollectionTypeEnum.link
    ) {
      return [
        {
          key: 0,
          title: '原文',
        },
        {
          key: 1,
          title: '切片',
        },
      ];
    }
    // if (
    //   collectionData?.type === DatasetCollectionTypeEnum.video
    // ) {
    //   return [
    //     {
    //       key: 0,
    //       title: '原视频',
    //     },
    //     {
    //       key: 1,
    //       title: '切片',
    //     },

    //   ];
    // }
    // if (
    //   collectionData?.type === DatasetCollectionTypeEnum.img
    // ) {
    //   return [
    //     {
    //       key: 0,
    //       title: '原图',
    //     },
    //     {
    //       key: 1,
    //       title: '切片',
    //     },

    //   ];
    // }
    return [
      {
        key: 1,
        title: '切片',
      },
    ];
  }, [collectionData]);

  const handleMenuClick = (index: number) => {
    setSelectedIndex(index);
    setActiveKeys((prev) => new Set([...prev, index]));
  };

  const handleAddChunk = async (q: string, a: string) => {
    try {
      const res = await datasetService.insertData({
        collectionId: collectionId,
        q: q,
        a: a,
        indexes: [],
      });
      message.success('添加成功');
      setNewChunkModal(false);
      event$?.emit(CollectionEvent.UPDATECOLLECTIONDATAS);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    if (menus.length == 1) {
      handleMenuClick(1);
    } else if (menus.length == 2) {
      handleMenuClick(0);
    }
  }, [menus]);

  useEffect(() => {
    setName(name);
  }, [name]);

  useEffect(() => {
    setCollectionId(collectionId);
  }, [collectionId]);

  return (
    <div className="flex h-full overflow-hidden">
      <div
        className={`flex h-full flex-col p-4 ${
          themeLayout !== ThemeLayout.Horizontal ? 'w-4/5' : 'w-full'
        }`}
        style={{ height: 'calc(100% - 20px)' }}
      >
        <div className="flex h-auto items-center">
          {onBack ? <Back onBack={onBack} /> : <Back />}
          <Ellipsis
            className="w-2/5"
            style={{ fontSize: '16px', fontWeight: 'bold' }}
            content={name}
            rows={1}
          />
        </div>
        <TabMenus
          className="my-3 flex-1 border-b border-line-2"
          menus={menus}
          selectedIndex={selectedIndex}
          onChange={handleMenuClick}
        />
        <div
          className="h-full w-full flex-grow overflow-hidden"
          style={{ display: selectedIndex === 1 ? 'none' : 'block' }}
        >
          {activeKeys.has(0) && collectionId && <PreviewCollection />}
        </div>
        <div
          className="h-full w-full flex-grow overflow-hidden"
          style={{ display: selectedIndex === 0 ? 'none' : 'block' }}
        >
          {activeKeys.has(1) && collectionId && (
            <div>
              <CollectionHeader
                className="mr-auto w-1/3"
                onChange={setSearchText}
                onInsert={() => {
                  setNewChunkModal(true);
                }}
              />
              <Chunks searchText={searchText} collectionId={collectionId} />
            </div>
          )}
        </div>
      </div>
      {themeLayout !== ThemeLayout.Horizontal && (
        <div className="flex" style={{ width: '474px', height: 'calc(100% - 20px)' }}>
          <Metadata />
        </div>
      )}
    </div>
  );
});

function CollectionProvider({ collectionId, name, onBack }: Props) {
  return (
    <CollectionContextProvider>
      <ChunksDetail collectionId={collectionId} name={name} onBack={onBack} />
    </CollectionContextProvider>
  );
}

export default memo(CollectionProvider);
